package com.example.gokchinesefoodmapmcdev.filter;

import com.alibaba.druid.support.json.JSONUtils;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.example.gokchinesefoodmapmcdev.util.JWTUtils;
import com.example.gokchinesefoodmapmcdev.util.ResultData;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;

/**
 * 自定义JWT token验证过滤器
 */
@Component
public class JWTTokenAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JWTUtils jwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setContentType("application/json;charset=utf8");

        // 1. 携带token的请求使用GET方式，token带在参数后
        String token = request.getParameter("token");
        // String token = request.getHeader("token");

        if (token == null) {
            filterChain.doFilter(request, response);
            return;
        }

        /*
            2. 获取到token信息，进行校验
                  如果校验失败，则会抛出对应的异常信息
         */
        try {
            jwtUtils.verify(token);
        } catch (JWTVerificationException e) {
            logger.error(e.getMessage(), e.getCause());
            response.getWriter().print(new ObjectMapper().writeValueAsString(ResultData.fail(ResultData.VERIFY_FAIL, "token有误，请登录后再做尝试")));
            return;
        }

        // 3. 取出token中存放的简单用户信息，将结果放入SecurityContextHolder中
        String username = jwtUtils.getValue(token, "username", String.class);
        String[] roles = jwtUtils.getArrayValue(token, "roles", String.class);
        Collection<GrantedAuthority> authorities = new HashSet<>();
        if (roles.length > 0) {
            for (String role : roles) {
                authorities.add(new SimpleGrantedAuthority(role));
            }
        }
        UserDetails userDetails = new User(
                username, "",
                true, true, true, true,
                authorities);

        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authentication);

        // 5. 放行
        filterChain.doFilter(request, response);

    }
}
